package online.westonline.com.westonline.ui;

import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alamkanak.weekview.WeekViewEvent;
import com.easy.west.westclient.api.base.bean.SuccessBean;
import com.easy.west.westclient.api.workplan.event.UploadPlanEvent;
import com.github.lzyzsd.circleprogress.ArcProgress;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.iwgang.countdownview.CountdownView;
import cn.qqtheme.framework.picker.DatePicker;
import cn.qqtheme.framework.picker.TimePicker;
import online.westonline.com.westonline.MyApplication;
import online.westonline.com.westonline.R;
import online.westonline.com.westonline.base.BaseActivity;
import online.westonline.com.westonline.entry.EventModel;
import online.westonline.com.westonline.utils.ToastUtils;
import online.westonline.com.westonline.utils.UiUtlis;

public class WorkPlanInfoActivity extends BaseActivity {


    @BindView(R.id.tv_topbar_title)
    TextView tvTopbarTitle;
    @BindView(R.id.tv_topbar_title_center)
    TextView tvTopbarTitleCenter;
    @BindView(R.id.img_toolbar_menu)
    ImageView imgToolbarMenu;
    @BindView(R.id.tv_topbar_menu)
    TextView tvTopbarMenu;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.arc_progress)
    ArcProgress arcProgress;
    @BindView(R.id.tv_plan_state)
    TextView tvPlanState;
    @BindView(R.id.count_down_view)
    CountdownView countDownView;
    @BindView(R.id.tv_time_date)
    TextView tvTimeDate;
    @BindView(R.id.tv_info_start_time)
    TextView tvInfoStartTime;
    @BindView(R.id.tv_info_end_time)
    TextView tvInfoEndTime;
    @BindView(R.id.check_change_allday)
    CheckBox checkChangeAllday;
    @BindView(R.id.ra_allday_layout)
    RelativeLayout raAlldayLayout;
    @BindView(R.id.tv_content)
    EditText tvContent;
    @BindView(R.id.tv_paln_delete)
    TextView tvPalnDelete;
    @BindView(R.id.btn_chage_plan)
    Button btnChagePlan;
    @BindView(R.id.check_top_today)
    CheckBox checkTopToday;
    @BindView(R.id.ra_top_check)
    RelativeLayout raTopCheck;
    @BindView(R.id.check_one_today)
    CheckBox checkOneToday;
    @BindView(R.id.ra_one_check)
    RelativeLayout raOneCheck;
    @BindView(R.id.check_two_today)
    CheckBox checkTwoToday;
    @BindView(R.id.ra_two_check)
    RelativeLayout raTwoCheck;
    @BindView(R.id.check_three_today)
    CheckBox checkThreeToday;
    @BindView(R.id.ra_three_check)
    RelativeLayout raThreeCheck;
    @BindView(R.id.check_four_today)
    CheckBox checkFourToday;
    @BindView(R.id.ra_four_check)
    RelativeLayout raFourCheck;
    @BindView(R.id.li_time_select)
    LinearLayout liTimeSelect;
    private EventModel plan;
    private WeekViewEvent event;
    private String selectday;
    private int start_hour;
    private int start_minute;
    private long time_start;
    private long time_end;
    private boolean edit_mode = false;
    private boolean canupload;
    private TimePicker startpicker;
    private TimePicker endpicker;
    private DatePicker datePicker;
    private int now_month_day;
    private int now_month;
    private int now_year;
    private int end_hour;
    private int select_year;
    private int select_month;
    private int select_month_day;
    private int end_minute;
    private String mEndTime;
    private String mStartTime;
    private String before_content;

    @Override
    protected void initview() {
        //初始化toolbar
        toolbar.setPopupTheme(R.style.Theme_AppCompat_Light_DarkActionBar);
        toolbar.setTitleTextColor(UiUtlis.getColor(R.color.colorMenuBtn));
        toolbar.setTitle("日程详情");
        tvTopbarMenu.setText("修改");
        tvTopbarMenu.setTextColor(UiUtlis.getColor(R.color.BlueTheme));
        toolbar.setBackgroundColor(UiUtlis.getColor(R.color.colorAppTheme));
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(true);
        //之前的content
        before_content = tvContent.getText().toString();
        //进度条初始化
        initprogress();
        //初始化视图
        initui();
        //初始化事件
        initsession();
    }

    private void initcountview() {
        //现在的时间减去开始时间
        //1.获取当前时间毫秒值
        long nowtime = System.currentTimeMillis();
        long endtime = event.getEndTime().getTime().getTime();
        long cast_time = endtime - nowtime;
        countDownView.start(cast_time);
    }

    private void initsession() {
        //设置点击事件
        tvInfoStartTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (edit_mode)
                {
                    startpicker.show();
                }
            }
        });
        tvInfoEndTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (edit_mode)
                {
                    endpicker.show();
                }
            }
        });
        tvTimeDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (edit_mode)
                {
                    datePicker.show();
                }
            }
        });
        //日期选择器监听
        datePicker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                select_year = Integer.parseInt(year);
                select_month = Integer.parseInt(month);
                select_month_day = Integer.parseInt(day);
                if (select_year<now_year)
                {
                    ToastUtils.showToast("不能在过去创建计划");
                    return;
                }
                if (select_month==now_month)
                {
                    if (select_month_day<now_month_day)
                    {
                        ToastUtils.showToast("不能在过去创建计划");
                        return;
                    }
                }
                if (select_year==now_year)
                {
                    if (select_month<now_month)
                    {
                        ToastUtils.showToast("不能在过去创建计划");
                        return;
                    }
                }
                tvTimeDate.setText(select_year+"-"+select_month+"-"+select_month_day);
            }
        });
        endpicker.setOnTimePickListener(new TimePicker.OnTimePickListener() {
            @Override
            public void onTimePicked(String hour, String minute) {
                //选择结束时间
                if (!tvTimeDate.getText().equals("点击选择日期"))
                {
                    String hour_str = hour;
                    String minute_str = minute;
                    end_hour = Integer.parseInt(hour);
                    end_minute = Integer.parseInt(minute);
                    //判断是否同一天（不用了）
                    if (end_hour<start_hour)
                    {
                        ToastUtils.showToast("结束时间不能低于开始时间或执行时间太短");
                        return;
                    }
                    if (end_hour==start_hour)
                    {
                        if (end_minute<start_minute||end_minute==start_minute)
                        {
                            ToastUtils.showToast("结束时间不能低于开始时间或执行时间太短");
                            return;
                        }
                    }
                    if (end_hour < 10) {
                        hour_str = "0" + start_hour;
                    }
                    if (end_minute < 10) {
                        minute_str = "0" + start_minute;
                    }
                    tvInfoEndTime.setText(hour_str+":"+minute_str);
                    mEndTime=hour_str+":"+minute_str;
                }
                else
                {
                    ToastUtils.showToast("请先选择日期");
                }

            }
        });
        //时间选择器的监听
        startpicker.setOnTimePickListener(new TimePicker.OnTimePickListener() {
            @Override
            public void onTimePicked(String hour, String minute) {
                if (!tvTimeDate.getText().equals("点击选择日期"))
                {

                    String hour1_str = hour;
                    String minute1_str = minute;
                    //未选择开始时间
                    start_hour = Integer.parseInt(hour);
                    start_minute = Integer.parseInt(minute);
                    if (start_hour < 10) {
                        hour1_str = "0" + start_hour;
                    }
                    if (start_minute < 10) {
                        minute1_str = "0" + start_minute;
                    }
                    tvInfoStartTime.setText(hour1_str + ":" + minute1_str);
                    mStartTime = hour1_str + ":" + minute1_str;
                }
                else
                {
                    ToastUtils.showToast("请先选择日期");
                }
            }

        });
        //置顶监听
        raTopCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkTopToday.setChecked(!checkTopToday.isChecked());
            }
        });
        //置顶
        checkTopToday.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                plan.setMAllday(isChecked);
                if (isChecked) {
                    checkTwoToday.setChecked(false);
                    checkThreeToday.setChecked(false);
                    checkOneToday.setChecked(false);
                    checkFourToday.setChecked(false);
                    tvInfoEndTime.setClickable(false);
                    tvInfoEndTime.setText("全天计划");
                    tvInfoStartTime.setClickable(false);
                    tvInfoStartTime.setText("全天计划");
                    //起始时间应为全天
                    plan.setMStartTime("00:00");
                    plan.setMEndTime("23:59");
                    tvInfoStartTime.setTextColor(UiUtlis.getColor(R.color.colorMenuBtn));
                    tvInfoEndTime.setTextColor(UiUtlis.getColor(R.color.colorMenuBtn));
                    canupload = true;

                } else {
                    tvInfoStartTime.setClickable(true);
                    tvInfoStartTime.setText("开始时间");
                    tvInfoEndTime.setClickable(true);
                    tvInfoEndTime.setText("结束时间");
                    canupload = false;
                }
            }
        });
        //上午选择
        raOneCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkOneToday.setChecked(!checkOneToday.isChecked());
            }
        });
        //中午选择
        raTwoCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkTwoToday.setChecked(!checkTwoToday.isChecked());
            }
        });
        //下午选择
        raThreeCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkThreeToday.setChecked(!checkThreeToday.isChecked());
            }
        });
        //checkbox监听
        checkOneToday.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    setedit(false);
                    //设置为今天
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.SIMPLIFIED_CHINESE);
                    plan.setDate(simpleDateFormat.format(System.currentTimeMillis()));
                    //时间9:00~12:00
                    checkThreeToday.setChecked(false);
                    checkTwoToday.setChecked(false);
                    checkTopToday.setChecked(false);
                    checkFourToday.setChecked(false);
                    tvInfoStartTime.setText("9:00");
                    tvInfoEndTime.setText("12:00");
                    plan.setMStartTime("9:00");
                    plan.setMEndTime("12:00");
                    canupload = true;

                } else {
                    setedit(true);
                    canupload = false;
                }
            }
        });
        checkTwoToday.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    setedit(false);
                    //设置为今天
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.SIMPLIFIED_CHINESE);
                    plan.setDate(simpleDateFormat.format(System.currentTimeMillis()));
                    //时间9:00~12:00
                    checkOneToday.setChecked(false);
                    checkThreeToday.setChecked(false);
                    checkTopToday.setChecked(false);
                    checkFourToday.setChecked(false);
                    tvInfoStartTime.setText("12:00");
                    tvInfoEndTime.setText("14:00");
                    plan.setMStartTime("12:00");
                    plan.setMEndTime("14:00");
                    canupload = true;

                } else {
                    setedit(true);
                    canupload = false;
                }
            }
        });
        checkThreeToday.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    setedit(false);
                    //设置为今天
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.SIMPLIFIED_CHINESE);
                    plan.setDate(simpleDateFormat.format(System.currentTimeMillis()));
                    //tvStartDay.setText(simpleDateFormat.format(System.currentTimeMillis()));
                    //时间9:00~12:00
                    checkOneToday.setChecked(false);
                    checkTwoToday.setChecked(false);
                    checkTopToday.setChecked(false);
                    checkFourToday.setChecked(false);
                    tvInfoStartTime.setText("14:00");
                    tvInfoEndTime.setText("18:00");
                    plan.setMStartTime("14:00");
                    plan.setMEndTime("18:00");
                    canupload = true;

                } else {
                    setedit(true);
                    canupload = false;
                }
            }
        });
        checkFourToday.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    setedit(false);
                    //设置为今天
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.SIMPLIFIED_CHINESE);
                    plan.setDate(simpleDateFormat.format(System.currentTimeMillis()));
                    //tvStartDay.setText(simpleDateFormat.format(System.currentTimeMillis()));
                    checkOneToday.setChecked(false);
                    checkTwoToday.setChecked(false);
                    checkTopToday.setChecked(false);
                    checkThreeToday.setChecked(false);
                    //时间9:00~12:00
                    tvInfoStartTime.setText("19:00");
                    tvInfoEndTime.setText("23:59");
                    plan.setMStartTime("19:00");
                    plan.setMEndTime("23:59");
                    canupload = true;

                } else {
                    setedit(true);
                    canupload = false;
                }
            }
        });
        tvPalnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (edit_mode)
                {
                    String content = tvContent.getText().toString();
                    if (TextUtils.isEmpty(content))
                    {
                        ToastUtils.showToast("无内容");
                        return;
                    }
                    if (tvTimeDate.getText().equals("点击选择日期"))
                    {
                        ToastUtils.showToast("未选择日期");
                        return;
                    }
                    if (
                            checkFourToday.isChecked()==false
                                    &&checkOneToday.isChecked()==false
                                    &&checkThreeToday.isChecked()==false
                                    &&checkTopToday.isChecked()==false
                                    &&checkTwoToday.isChecked()==false)
                    {
                        if (mStartTime==null||mEndTime==null) {
                            ToastUtils.showToast("请设置时间范围");
                            return;
                        }
                    }
                    plan.setDate(tvTimeDate.getText().toString());
                    plan.setDay(select_month_day);
                    plan.setMName(content);
                    plan.setMAllday(checkTopToday.isChecked());
                    if (checkTopToday.isChecked())
                    {
                        plan.setMStartTime("00:00");
                        plan.setMEndTime("23:59");
                    }
                    else
                    {
                        plan.setMStartTime(tvInfoStartTime.getText().toString());
                        plan.setMEndTime(tvInfoEndTime.getText().toString());
                    }
                    plan.setMColor(UiUtlis.RandomColor());
                    plan.setYear(select_year);
                    plan.setMonth(select_month);
                    //预留
                    MyApplication.getClient().changeWorkPlan(
                            plan.getId(),
                            plan.getMStartTime(),
                            plan.getMEndTime()
                            ,plan.getMName()
                            ,plan.getDate()
                            ,plan.getMAllday()
                            ,1);
                }
                else
                {
                    MyApplication.getClient().delete(plan.getId());
                }

            }
        });
        //修改
        tvTopbarMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (edit_mode) {
                    if (!TextUtils.isEmpty(before_content))
                    {
                        tvContent.setText(before_content);
                    }
                    edit_mode = false;
                    liTimeSelect.setVisibility(View.GONE);
                    //初始化状态
                    tvTopbarMenu.setText("修改");
                    tvContent.setEnabled(false);
                    tvPalnDelete.setText("删除");
                    checkFourToday.setChecked(false);
                    checkOneToday.setChecked(false);
                    checkTopToday.setChecked(false);
                    checkThreeToday.setChecked(false);
                    checkTwoToday.setChecked(false);
                } else {
                    edit_mode = true;
                    tvTopbarMenu.setText("取消");
                    tvPalnDelete.setText("保存");
                    //编辑啦
                    tvContent.setEnabled(true);
                    liTimeSelect.setVisibility(View.VISIBLE);

                }
            }
        });
    }
    /**
     * 设置控件属性
     */
    private void setedit(boolean flag) {
        tvInfoEndTime.setClickable(flag);
        
        tvInfoStartTime.setClickable(flag);
        if (flag)
        {
            tvInfoStartTime.setText("开始时间");
            tvInfoEndTime.setText("结束时间");
        }
        //全部初始化
    }
    private void initprogress() {
        //计算进度条
        //1.当前日期是否与日程日期相同
        int targetday = event.getStartTime().get(Calendar.DAY_OF_MONTH);
        int today = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
        //1.当前月份获取
        int nowmonth = Calendar.getInstance().get(Calendar.MONTH) + 1;
        int targetmonth = event.getStartTime().get(Calendar.MONTH) + 1;
        //获取现在的时间
        long nowtime = System.currentTimeMillis();
        if (targetday < today) {
            //昨天的事情了
            arcProgress.setBottomText("计划已结束");
            arcProgress.setProgress(100);
            tvPlanState.setVisibility(View.GONE);
            countDownView.setVisibility(View.GONE);
        }
        if (targetday == today) {
            //当天
            //条件为计算范围
            if (nowtime >= time_start && nowtime < time_end) {
                long totaltime = 0;
                int start_hour = event.getStartTime().get(Calendar.HOUR_OF_DAY);
                int start_minut = event.getStartTime().get(Calendar.MINUTE);
                int end_hor = event.getEndTime().get(Calendar.HOUR_OF_DAY);
                int end_minute = event.getEndTime().get(Calendar.MINUTE);
                if (start_hour == end_hor) {
                    //同一小时内
                    totaltime = (end_minute - start_minut) * 60 * 1000;
                } else {
                    long hourtime = (end_hor - start_hour) * 3600 * 1000;
                    totaltime = hourtime;
                    if (end_minute == start_minut) {
                        totaltime = hourtime;
                    }
                    if (end_minute > start_minut) {
                        totaltime = hourtime + (end_minute - start_minut) * 60 * 1000;
                    }
                    if (end_minute < start_hour) {
                        totaltime = hourtime + (start_minut - end_hor) * 60 * 1000;
                    }
                }
                //获取现在的时间（时分）
                int nowhour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
                int nowminute = Calendar.getInstance().get(Calendar.MINUTE);
                long nowtime1 = (nowhour * 3600 * 1000 + nowminute * 60 * 1000) - (start_hour * 3600 * 1000 + start_minut * 60 * 1000);
                long casttime = totaltime - nowtime1;
                int progress = 100 - (int) (casttime * 100 / totaltime);
                if (progress == 0) {
                    progress = 100;
                }
                arcProgress.setBottomText("进度");
                arcProgress.setProgress(progress);
                initcountview();
                if (progress == 100) {
                    arcProgress.setBottomText("计划已结束");
                    tvPlanState.setVisibility(View.GONE);
                    countDownView.setVisibility(View.GONE);
                }

            }
            if (nowtime >= time_end) {
                //已过日程时间
                arcProgress.setBottomText("计划已结束");
                tvPlanState.setVisibility(View.GONE);
                countDownView.setVisibility(View.GONE);
                arcProgress.setProgress(100);
            }
            if (nowtime < time_start) {
                //日程未开始
                arcProgress.setBottomText("计划未开始");
                arcProgress.setProgress(0);
            }
        }
        if (targetday > today) {
            arcProgress.setBottomText("计划未开始");
            arcProgress.setProgress(0);
        }
        if (nowmonth > targetmonth) {
            arcProgress.setBottomText("计划已结束");
            arcProgress.setProgress(100);
            tvPlanState.setVisibility(View.GONE);
            countDownView.setVisibility(View.GONE);
        }
    }

    //初始化ui
    private void initui() {
        checkChangeAllday.setChecked(event.isAllDay());
        tvContent.setText(event.getName());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.SIMPLIFIED_CHINESE);
        String date = simpleDateFormat.format(event.getStartTime().getTime());
        int start_hour = event.getStartTime().get(Calendar.HOUR_OF_DAY);
        int start_minut = event.getStartTime().get(Calendar.MINUTE);
        int end_hor = event.getEndTime().get(Calendar.HOUR_OF_DAY);
        int end_minute = event.getEndTime().get(Calendar.MINUTE);
        String formatminute = start_minute + "";
        if (start_minute < 10) {
            formatminute = "0" + start_minute;
        }
        if (start_minute == 0) {
            formatminute = "00";
        }
        String end_formatminute = end_minute + "";
        if (end_minute < 10) {
            end_formatminute = "0" + end_minute;
        }
        if (end_minute == 0) {
            end_formatminute = "00";
        }
        plan.setMStartTime(start_hour + ":" + formatminute);
        plan.setMEndTime(end_hor + ":" + end_formatminute);
        plan.setDate(date);
        tvTimeDate.setText(date);
        tvInfoStartTime.setText(start_hour + ":" + formatminute);
        tvInfoEndTime.setText(end_hor + ":" + end_formatminute);
        if (event.isAllDay()) {
            tvInfoEndTime.setText("全天");
            tvInfoStartTime.setText("全天");
        }
    }

    @Override
    protected void initdata() {
        //选择器初始化
        startpicker = new TimePicker(this);
        endpicker = new TimePicker(this);
        datePicker = new DatePicker(this);
        //今日
        now_month_day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
        //现在月份
        now_month = Calendar.getInstance().get(Calendar.MONTH) + 1;
        //当前年份
        now_year = Calendar.getInstance().get(Calendar.YEAR);
        datePicker.setRangeStart(now_year,now_month,now_month_day);
        datePicker.setRangeEnd(now_year,12,31);
        datePicker.setSelectedItem(now_year,now_month,now_month_day);
        datePicker.setLineSpaceMultiplier(4);
        event = (WeekViewEvent) getIntent().getExtras().getSerializable("event");
        //填充原始体
        plan = new EventModel();
        plan.setId(event.getId());
        plan.setMName(event.getName());
        plan.setMAllday(event.isAllDay());
        inittime();
    }

    /**
     * 计算时间
     */
    private void inittime() {
        //转换
        time_start = event.getStartTime().getTime().getTime();
        time_end = event.getEndTime().getTime().getTime();
    }

    @Override
    protected int setlayout() {
        return R.layout.activity_work_plan_info;
    }

    /***
     * 删除和修改计划
     * @param eva
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changePlan(UploadPlanEvent eva) {
        if (eva.isOk()) {
            SuccessBean ss = eva.getBean();
            ToastUtils.showToast("操作成功");
            finish();
        }
    }


}
